package com.campus.bbs;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class ListContoller implements OnItemClickListener, OnScrollListener {
	ListView listview;
	GetITieInfo getEngine;
	ArrayList<TieInfo> list;
	TieAdapter adapter;

	public ListContoller(Context context) {
		listview = new ListView(context);
		getEngine = new GetMob();
		list = new ArrayList();
		this.context = context;
		adapter = new TieAdapter(context, list);
		listview.setAdapter(adapter);
		listview.setOnScrollListener(this);
		listview.setOnItemClickListener(this);
		go();
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if (firstVisibleItem == 0) {
			// Log.e("log", "滑到顶部");
		}
		if (visibleItemCount + firstVisibleItem == totalItemCount) {
			// Log.e("log", "滑到底部");
			go();
		}
	}

	View getView() {
		return listview;
	}

	void go() {
		new Thread() {
			public void run() {

				try {
					list.addAll(getEngine.getTieInfoList());
					Handler handler = new Handler(Looper.getMainLooper());
					handler.post(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							adapter.notifyDataSetChanged();
						}
					});
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}.start();
	}

	Context context;

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		// TODO Auto-generated method stub
		DetailActivity.send((Activity) context, list.get(position).url);
	}
}
